import 'package:fate_blind_box/config/app_style.dart';
import 'package:fate_blind_box/widget/code_input_item.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

/// 验证码输入框
///
class CodeInputWidget extends StatefulWidget {
  const CodeInputWidget({
    super.key,
    this.count = 6,
    this.height = 44,
    this.itemWidth = 44,
    this.showCursor = false,
    this.onSubmitted,
    this.unfocus = true,
    this.autoFocus = true,
    this.obscureText = false,
    this.obscuringCharacter = '*',
    this.controller,
  });

  /// 验证码个数
  final int count;

  /// 验证码输入widget高度
  final double height;

  /// 每一个item宽度/高度
  final double itemWidth;

  /// 是否显示光标
  final bool showCursor;

  /// 输入完成回调
  final ValueChanged<String>? onSubmitted;

  /// 输入完成后是否失去焦点，默认true，失去焦点后，键盘消失
  final bool unfocus;

  /// 是否自动获取焦点, 默认true
  final bool autoFocus;

  /// 是否是密码类型，默认false
  final bool obscureText;

  /// 密码类型字符，默认*
  final String obscuringCharacter;

  final TextEditingController? controller;

  @override
  State<CodeInputWidget> createState() => _CodeInputWidgetState();
}

class _CodeInputWidgetState extends State<CodeInputWidget> {
  late TextEditingController _textEditingController;
  late FocusNode _focusNode;
  final List<String> _contentList = [];

  @override
  void initState() {
    _textEditingController = widget.controller ?? TextEditingController();
    _focusNode = FocusNode();
    List.generate(widget.count, (index) {
      _contentList.add('');
    });

    _textEditingController.addListener(() {
      if (_textEditingController.text.isEmpty) {
        _onValueChange(_textEditingController.text);
      }
    });

    super.initState();
  }

  @override
  void dispose() {
    if (widget.controller == null) {
      _textEditingController.dispose();
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        FocusScope.of(context).requestFocus(_focusNode);
      },
      child: SizedBox(
        height: widget.height,
        child: Stack(
          children: <Widget>[
            Positioned.fill(
              /// 验证码输入框列表
              child: _buildInputBoxListWidget(),
            ),
            _buildTextField(),
          ],
        ),
      ),
    );
  }

  /// 验证码输入框列表
  Widget _buildInputBoxListWidget() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: List.generate(widget.count, (index) {
        return _buildInputItem(
          index: index,
        );
      }),
    );
  }

  /// textField
  Widget _buildTextField() {
    return TextField(
      controller: _textEditingController,
      focusNode: _focusNode,
      obscureText: widget.obscureText,
      obscuringCharacter: widget.obscuringCharacter,
      decoration: const InputDecoration(
        border: UnderlineInputBorder(
          borderSide: BorderSide(color: Colors.transparent),
        ),
        enabledBorder: UnderlineInputBorder(
          borderSide: BorderSide(color: Colors.transparent),
        ),
        focusedBorder: UnderlineInputBorder(
          borderSide: BorderSide(color: Colors.transparent),
        ),
      ),
      cursorWidth: 0,
      autofocus: widget.autoFocus,
      inputFormatters: [
        FilteringTextInputFormatter.allow(RegExp("[0-9]")),
      ],
      maxLength: widget.count,
      buildCounter: (
        BuildContext context, {
        required int currentLength,
        required bool isFocused,
        required int? maxLength,
      }) {
        return const Text('');
      },
      keyboardType: TextInputType.number,
      style: const TextStyle(color: Colors.transparent),
      enableInteractiveSelection: false,
      onChanged: (value) {
        if (value.isNotEmpty) {
          _onValueChange(value);
        }
      },
    );
  }

  /// 输入值改变
  void _onValueChange(value) {
    for (int i = 0; i < widget.count; i++) {
      if (i < value.length) {
        _contentList[i] = value.substring(i, i + 1);
      } else {
        _contentList[i] = '';
      }
    }
    setState(() {});

    if (value.length == widget.count) {
      if (widget.unfocus) {
        _focusNode.unfocus();
      }
      widget.onSubmitted?.call(value);
    }
  }

  /// 单个验证码item
  Widget _buildInputItem({required int index}) {
    return SizedBox(
      width: widget.itemWidth,
      child: CodeInputItem(
        data: maskString(_contentList[index]),
        textStyle: TextStyle(
          color: const Color(0xFF1D2129),
          fontSize: widget.obscureText ? 40 : 20,
          fontWeight: FontWeight.w600,
          fontFamily: 'PingFang SC',
        ),
        showCursor:
            widget.showCursor && _textEditingController.text.length == index,
        cursorColor: '1D2129'.stringToColor,
        cursorWidth: 1,
        cursorIndent: 5,
        cursorEndIndent: 5,
        decoration: ShapeDecoration(
          shape: RoundedRectangleBorder(
            side: BorderSide(
                width: 1,
                color: (_textEditingController.text.length >= index
                    ? '4E5969'.stringToColor
                    : 'C9CDD4'.stringToColor)),
            borderRadius: BorderRadius.circular(8),
          ),
        ),
      ),
    );
  }

  // 使用replaceAll函数将字符串中的每个字符替换为*
  String maskString(String str) {
    if (!widget.obscureText) {
      return str;
    }
    String maskedStr = str.replaceAll(RegExp(r'.'), widget.obscuringCharacter);
    return maskedStr;
  }
}
